package org.yly.game.rpggame.domain.model.goods;

import org.yly.game.rpggame.domain.model.DomainEventPublisher;

public class GoodsState {

	public static final int Unbind = 1; //
	public static final int Bind = 2; // 已经绑定
	public static final int Using = 4; // 已经使用
	public static final int Unusing = 8; // 已经销毁
	public static final int Lock = 16; // 已经销毁
	public static final int Unlock = 32; // 已经锁定
	public static final int Destroy = 64; // 已经锁定

	private int value = 41;
	
	private String goodsId;
	
	public GoodsState(String goodsId){
		this.goodsId = goodsId;
	}

	private void setState(int state) {
		if (this.contain(Destroy)) {
			throw new IllegalStateException("物品物品已经销毁");
		}
		if (Unlock == state) {
			throw new IllegalStateException("物品不能解锁定");
		}
		if (Bind == state && !this.contain(Unbind)) {
			throw new IllegalStateException("物品已绑定");
		}
		if (!this.contain(Bind)) {
			throw new IllegalStateException("物品未绑定");
		}
		if (Unbind == state && !this.contain(Unusing)) {
			throw new IllegalStateException("物品使用中");
		}
		if (Unbind == state && !this.contain(Unlock)) {
			throw new IllegalStateException("物品已锁定");
		}
		if (Using == state && !this.contain(Unusing)) {
			throw new IllegalStateException("物品使用中");
		}
		if (Unusing == state && !this.contain(Using)) {
			throw new IllegalStateException("物品未使用");
		}
		if (Lock == state && !this.contain(Unlock)) {
			throw new IllegalStateException("物品已锁定");
		}
		if (Destroy == state && !this.contain(Unusing)) {
			throw new IllegalStateException("物品使用中");
		}
		if (Unbind == state) {
			this.value = (this.value & (~Bind));
		}
		if (Bind == state) {
			this.value = (this.value & (~Unbind));
		}
		if (Using == state) {
			this.value = (this.value & (~Unusing));
		}
		if (Unusing == state) {
			this.value = (this.value & (~Using));
		}
		if (Lock == state) {
			this.value = (this.value & (~Unlock));
		}
		if (Destroy == state) {
			this.value = Destroy;
		} else {
			this.value |= state;
		}
		
		DomainEventPublisher.getInstance().publish(new GoodsStateChangeEvent(goodsId, this.value));
	}

	public boolean contain(int state) {
		return (this.value & state) == this.value;
	}

	public boolean isBind() {
		return this.contain(Bind);
	}

	public boolean isUsing() {
		return this.contain(Bind);
	}

	public boolean isLock() {
		return this.contain(Lock);
	}

	public boolean isDestroy() {
		return this.contain(Destroy);
	}

	public void Bind() {
		this.setState(Bind);
	}

	public void Unbind() {
		this.setState(Unbind);
	}

	public void Use() {
		this.setState(Using);
	}

	public void Unuse() {
		this.setState(Unusing);
	}

	public void Lock() {
		this.setState(Using);
	}

	public void Unlock() {
		this.setState(Unusing);
	}

	public void destroy() {
		this.setState(Destroy);
	}

}
